<?php

namespace app\admin\controller;

use app\models\Bases;
use think\Request;
use think\file;
use app\admin\validate;
/**
 * 视频回放控制器
 * @author wanglong <ycitwl@163.com>
 */
class Play extends Base 
{

	/**
	 * 视频回放列表
	 * @return [type] [description]
	 */
	public function playShow()
	{
		$playModel = new Bases('play');
		try{
            $get = input('param.');
            $search = search($get, 'create_time', 'title');
            $result = $playModel -> page($search['condition'], 'create_time desc', 15);
            if(empty($result)){
                throw new \LogicException("很遗憾，没有数据", 10013);
            }
            return view('playList',['result'=>$result, 'display'=>$get]);
		}catch(\Exception $e){
			return self::formatResult($e->getCode(), $e->getMessage());
		}
	}

	/**
	 * 新增视频回放记录
	 * @return [type] [description]
	 */
	public function playAdd()
	{
		$playModel = new Bases('play');
		try{
		    $type_id = empty(input('type_id'))?5:input('type_id');
			if(Request() -> isPost()){
				$post = input('param.');
                $post['type_id'] = $type_id;
                //标题不可为空
                if(empty($post['title'])){
                    throw new \LogicException('标题不可为空', 10013);
                }
				if(!empty($post['link_url'])){
					$link_address1 = mb_substr(trim($post['link_url']),0,7);
					$link_address2 = mb_substr(trim($post['link_url']),0,8);
					if(strpos($link_address1,'http://') === false && strpos($link_address2,'https://') === false){
						throw new \LogicException('链接地址必须以http://或者https://开头',10000);
					}
				}
				unset($post['image']);
				//获取上传文件
				if(empty($_FILES)){
					throw new \LogicException('上传失败', 1024);
				}
                $file = request() -> file('image');
				$info = $file ->validate(['size'=>200000,'ext'=>'jpg,png,gif'])->rule('uniqid')-> move(ROOT_PATH.'public'.DS.'uploads'.DS.'play');
				//上传成功获取文件信息
				if($info){
					$post['create_time'] = time();
					$post['image'] = $info->getFilename();
					$post['image_path'] = DS. 'uploads'.DS.'play'.DS.$post['image'];
					$result = $playModel ->insertData($post);
					if(!$result){
						throw new \LogicException('操作失败', 1024);
					}
					return self::formatSuccessResult();	
				}else{
					//上传失败
					throw new \LogicException($file->getError(),1024);
				}

			}
		}catch(\Exception $e){
			return self::formatResult($e->getCode(), $e->getMessage());
		}
		return view('playAdd');
	}

	/**
	 * 保存修改视频回放记录
	 * @return [type] [description]
	 */
	public function playSave()
	{
		$playModel = new Bases('play');
		$play_id = intval(input('id'));
        try{
            if(Request()->isPost()){
                $post = input('param.');
                $post['pid'] = $post['id'];
                //标题和链接不可为空
                if(empty($post['title']) ){
                    throw new \LogicException('标题不可为空', 10013);
                }
				if(!empty($post['link_url'])){
					$link_address1 = mb_substr(trim($post['link_url']),0,7);
					$link_address2 = mb_substr(trim($post['link_url']),0,8);
					if(strpos($link_address1,'http://') === false && strpos($link_address2,'https://') === false){
						throw new \LogicException('链接地址必须以http://或者https://开头',10000);
					}
				}
                unset($post['uploadfile']);
                unset($post['id']);
                //没改变图片,修改名称或链接
                if(array_key_exists('image', $post)){
                	$data = ['title'=>$post['title'], 'link_url'=>$post['link_url'], 'pid'=>$post['pid']];
                	$result = $playModel->updateData($data);
                	if(!$result){
                    	throw new \LogicException('未做更新', 1);
	                }
	                	return self::formatSuccessResult();                
	            }
	            //对上传图片做了修改
	            unset($post['uploadfile']);
                $file = request()->file('image');
                if($file){
                    // 移动上传图片
                    $info = $file->validate(['size'=>200000,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'play');
                    if($info){
                        // 成功上传后 获取上传信息
                        $post['image'] = $info->getFilename();
                        $post['image_path'] = DS.'uploads'.DS.'play'.DS.$post['image'];
                        $result = $playModel->updateData($post);
		                if(!$result){
		                    throw new \LogicException('更新失败',1024);
		                }
		                return self::formatSuccessResult();
                    }else{
                        // 上传失败
                        throw new \LogicException($file->getError(), 1024);
                    }
                }else{
                	throw new \LogicException('上传失败',1024);
                }
               
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        $where = array('pid'=>$play_id);
        $result = $playModel->find($where);
        return view('playSave',['result'=>$result]);
	}

	/**
	 * 删除视频回放
	 */
	public function playDel()
	{
		$playModel = new Bases('play');
		$play_id = intval(input('id'));
		try{
			$where['pid'] = $play_id;
			$imagepath = $playModel -> value($where,'image_path');
			$imageUrl = ROOT_PATH.'public'.$imagepath;
			//文件不存在，只删除数据库记录
			if(!file_exists($imageUrl)){
				$result = $playModel -> deleteDaPtaByPrimaryKey($play_id);
				if(empty($result)){
					throw new \LogicException('操作失败', 1024);
				}
				return self::formatSuccessResult();
			}
			//删除文件和数据库记录
			$delFile = unlink($imageUrl);
			if(!$delFile){
				throw new \LogicException(1024, '未能删除系统中的文件，文件指向可能不正确');
			}
			//删除mysql记录
			$result = $playModel -> deleteDaPtaByPrimaryKey($play_id);
			if(empty($result)){
				throw new \LogicException('操作失败', 1024);
			}
			return self::formatSuccessResult();
		}catch(\Exception $e){
			return self::formatResult($e->getCode(), $e->getMessage());
		}
	}

}